<template>
  <div class="app-container usercenter">
    <div class="usercenter-header">
      <el-button type="primary" size="mini" @click="dialog.createUser = true">新建用户</el-button>
    </div>
    <el-table
      :data="list"
      style="width: 100%">
      <el-table-column
        label="账号">
        <template slot-scope="scope">
          <div class="table-link">
            <span>{{ scope.row.account }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="邮箱">
        <template slot-scope="scope">
          <div class="table-link">
            <span>{{ scope.row.email }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="角色">
        <template slot-scope="scope">
          <div class="table-link">
            <span v-if="scope.row.email === 'administrator@management.local'">超级管理员</span>
            <span v-else>{{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="size"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <a class="table-action" @click="clickModifyUser(scope.row)">修改</a>
          <a class="table-action" @click="clickDeleteUser(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="basePagenate">
      <el-pagination
        :page-size="pageSize"
        :current-page="pageNumber"
        :total="totalPage"
        layout="prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div> -->
    <el-dialog
      :visible.sync="dialog.createUser"
      :title="dialog.editUser ? '修改用户' : '新建用户'"
      width="500px"
      @close="resetForm('createUserForm')">
      <el-form ref="createUserForm" :model="createUserForm" :rules="rulesCreateUser" label-width="80px">
        <el-form-item label="邮箱：" prop="email">
          <el-input :disabled="dialog.editUser" v-model="createUserForm.email" />
        </el-form-item>
        <el-form-item label="账号：" prop="account">
          <el-input :disabled="createUserForm.email === 'administrator@management.local' && dialog.editUser" v-model="createUserForm.account" />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="createUserForm.password" />
        </el-form-item>
        <el-form-item label="角色：" prop="role">
          <el-radio-group v-model="createUserForm.role">
            <el-radio v-if="createUserForm.email === 'administrator@management.local' && dialog.editUser" label="admin">超级管理员</el-radio>
            <el-radio v-if="createUserForm.email !== 'administrator@management.local'" label="admin">管理员</el-radio>
            <el-radio v-if="createUserForm.email !== 'administrator@management.local'" label="normal">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.createUser = false; dialog.editUser = false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('createUserForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { handleUser } from '@/api/usercenter'

export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9._-])+@([A-Za-z0-9d]+[-.])+[A-Za-zd]{2,5}$/
      if (value === '') {
        callback(new Error('请填写邮箱'))
      } else if (!reg.test(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    const checkAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请填写账号'))
      } else {
        callback()
      }
    }
    const checkPassword = (rule, value, callback) => {
      if (!this.dialog.editUser) {
        if (value === '') {
          callback(new Error('请填写密码'))
        } else if (value.length < 6) {
          callback(new Error('密码最小6位'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      list: null,
      listLoading: true,
      selCluster: '',
      clusterOptions: [],
      // 总页数
      totalPage: 0,
      // 每页条数
      pageSize: 20,
      // 当前页
      pageNumber: 1,
      dialog: {
        createUser: false,
        editUser: false
      },
      createUserForm: {
        email: '',
        account: '',
        password: '',
        role: 'admin'
      },
      rulesCreateUser: {
        email: [
          { validator: checkEmail }
        ],
        account: [
          { validator: checkAccount }
        ],
        password: [
          { validator: checkPassword }
        ]
      }
    }
  },
  created() {
    this._handleUser('Get')
  },
  methods: {
    // 修改用户
    clickModifyUser(row) {
      this.rulesCreateUser.account[0].required = false
      this.rulesCreateUser.password[0].required = false
      this.dialog.createUser = true
      this.dialog.editUser = true
      this.createUserForm.email = row.email
      this.createUserForm.account = row.account
      this.createUserForm.role = row.role
    },
    // 删除用户
    clickDeleteUser(row) {
      this.$confirm(`此操作将删除该用户${row.account}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          email: row.email
        }
        this._handleUser('Delete', data)
      })
    },
    // 表单提交(createUserForm: 新建用户)
    submitForm() {
      const method = this.dialog.editUser ? 'Put' : 'Post'
      this.$refs['createUserForm'].validate((valid) => {
        if (valid) {
          const data = {
            email: this.createUserForm.email,
            account: this.createUserForm.account,
            role: this.createUserForm.role
          }
          if (this.createUserForm.password) {
            data.password = this.createUserForm.password
          }
          this._handleUser(method, data)
          this.resetForm('createUserForm')
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      // this.rulesCreateUser.account[0].required = true
      // this.rulesCreateUser.password[0].required = true
      this.dialog.editUser = false
      this.dialog.createUser = false
      this.createUserForm = {
        email: '',
        account: '',
        password: '',
        role: 'admin'
      }
      this.$refs[formName].resetFields()
    },
    // 用户操作（查询列表：Get,新增：Post,修改：Put,删除：Delete）
    _handleUser(method, data) {
      this.listLoading = true
      handleUser(method, data).then(res => {
        if (res.message.code === 0) {
          this.listLoading = false
          switch (method) {
            case 'Get':
              this.list = res.data
              break
            case 'Post':
              this.$message({ message: '新建成功', showClose: true, type: 'success' })
              this._handleUser('Get')
              break
            case 'Put':
              this.$message({ message: '修改成功', showClose: true, type: 'success' })
              this._handleUser('Get')
              break
            case 'Delete':
              this.$message({ message: '删除成功', showClose: true, type: 'success' })
              this._handleUser('Get')
              break
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.usercenter {
  &-header {
    padding: 10px;
    background: #ffffff;
    font-size: 14px;
    color: #303133;
    font-weight: bold;
    .header-title {
      font-size: 14px;
      font-weight: 700;
    }
  }
  label {
    font-weight: normal
  }
  .table-action {
    color: #4285f4;
  }
  .table-link {
    &:hover {
      color: #4285f4;
    }
  }
}
</style>
